package gw.com.android.ui.chart.manager;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;

import com.gwtsz.chart.components.Legend;
import com.gwtsz.chart.components.LimitLine;
import com.gwtsz.chart.components.XAxis;
import com.gwtsz.chart.components.YAxis;
import com.gwtsz.chart.data.Entry;
import com.gwtsz.chart.data.LineData;
import com.gwtsz.chart.data.LineDataSet;
import com.gwtsz.chart.formatter.YAxisValueFormatter;
import com.gwtsz.chart.highlight.Highlight;
import com.gwtsz.chart.interfaces.datasets.ILineDataSet;
import com.gwtsz.chart.listener.OnChartValueSelectedListener;
import com.gwtsz.chart.output.bean.DataParse;
import com.gwtsz.chart.output.bean.KLineBean;
import com.gwtsz.chart.output.bean.MinutesBean;
import com.gwtsz.chart.output.customer.MyBottomMarkerView;
import com.gwtsz.chart.output.customer.MyLeftMarkerView;
import com.gwtsz.chart.output.customer.MyLineChart;
import com.gwtsz.chart.output.customer.MyRightMarkerView;
import com.gwtsz.chart.output.customer.MyXAxis;
import com.gwtsz.chart.output.customer.MyYAxis;
import com.gwtsz.chart.output.utils.ChartThemeUtil;
import com.gwtsz.chart.output.utils.GTTIndicatorsModel;
import com.gwtsz.gts2.hx.R;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import www.com.library.app.Logger;
import www.com.library.util.StringFormatter;

/**
 * Created by spence on 17-3-14.
 */
public class TimeChartControl implements ChartInterface{

    private static String TAG=TimeChartControl.class.getSimpleName();

    private static String METHOD="class="+TAG+" method=";

    MyLineChart lineChart;
    private LineDataSet d1, d2;
    MyXAxis xAxisLine;
    MyYAxis axisRightLine;
    MyYAxis axisLeftLine;
    private DataParse mData;
    Integer sum = 0;
    List<Integer> listA, listB;
    SparseArray<String> stringSparseArray;
    Context mContext;
    DecimalFormat mDecimalFormat;
    int mStartTime=0;
    MyLeftMarkerView leftMarkerView ;
    MyRightMarkerView rightMarkerView ;
    MyBottomMarkerView bottomMarkerView;

    TimeChartControl(MyLineChart myLineChart, Context context){
        lineChart=myLineChart;
        mContext=context;
        initChart();
        stringSparseArray = setXLabels();
        setShowLabels(stringSparseArray);
        mDecimalFormat=new DecimalFormat("#0.00");
         leftMarkerView = new MyLeftMarkerView(mContext, R.layout.mymarkerview);
         rightMarkerView = new MyRightMarkerView(mContext, R.layout.mymarkerview,mDecimalFormat);
         bottomMarkerView = new MyBottomMarkerView(mContext, R.layout.mymarkerview);
        lineChart.setMarker(leftMarkerView,rightMarkerView,bottomMarkerView);
    }


    public static TimeChartControl Build(MyLineChart myLineChart,Context context){
        return new TimeChartControl(myLineChart,context);
    }



    @Override
    public void refreshData(DataParse mData) {
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",mData="+mData);
        setData(mData);
    }

    @Override
    public void addMaxMinValue() {

    }

    @Override public void addDataToFoot(KLineBean kLineBean, GTTIndicatorsModel main,
        GTTIndicatorsModel second) {

    }

    @Override
    public void refreshFootData(KLineBean kLineBean, GTTIndicatorsModel mainIndicatorsModel,
        GTTIndicatorsModel secondIndicatorsModel) {

    }



    private void initChart() {
        lineChart.setMinOffset(0);
        lineChart.setExtraBottomOffset(12f);
        lineChart.setScaleEnabled(false);
        lineChart.setDrawBorders(false);
        //lineChart.setBorderWidth(1);
        lineChart.setBorderColor(ChartThemeUtil.instance().color_line);
        lineChart.setDescription("");
        Legend lineChartLegend = lineChart.getLegend();
        lineChartLegend.setEnabled(false);
        lineChart.setLogEnabled(false);
        lineChart.getRendererLeftYAxis().setNeutralColor(ChartThemeUtil.instance().IdleColor);
        lineChart.getRendererLeftYAxis().setDecreasingColor(ChartThemeUtil.instance().FallColor);
        lineChart.getRendererLeftYAxis().setIncreasingColor(ChartThemeUtil.instance().RiseColor);
        lineChart.getRendererRightYAxis().setNeutralColor(ChartThemeUtil.instance().IdleColor);
        lineChart.getRendererRightYAxis().setDecreasingColor(ChartThemeUtil.instance().FallColor);
        lineChart.getRendererRightYAxis().setIncreasingColor(ChartThemeUtil.instance().RiseColor);

        //x轴
        xAxisLine = lineChart.getXAxis();
        xAxisLine.setAxisLineColor(ChartThemeUtil.instance().color_line);
        xAxisLine.setDrawLabels(true);
        xAxisLine.setPosition(XAxis.XAxisPosition.BOTTOM);
        //xAxisLine.setLabelsToSkip(59);
        xAxisLine.enableGridDashedLine(4,3,0);
        xAxisLine.setSideNeedPathEffect(false);
        xAxisLine.setNeedShowSideLine(true);

        //左边y
        axisLeftLine = lineChart.getAxisLeft();
        /*折线图y轴左没有basevalue，调用系统的*/
        axisLeftLine.setAxisLineColor(ChartThemeUtil.instance().color_line);
        axisLeftLine.setLabelCount(7, true);
        axisLeftLine.setDrawLabels(true);
        axisLeftLine.setDrawGridLines(true);
        axisLeftLine.enableGridDashedLine(4,3,0);
        /*轴不显示 避免和border冲突*/
        axisLeftLine.setDrawAxisLine(false);
        axisLeftLine.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        axisLeftLine.setSideNeedPathEffect(false);
        axisLeftLine.setNeedOffset(false);



        //右边y
        axisRightLine = lineChart.getAxisRight();
        axisRightLine.setLabelCount(7, true);
        axisRightLine.setDrawLabels(true);
        axisRightLine.setValueFormatter(new YAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, YAxis yAxis) {
                DecimalFormat mFormat = new DecimalFormat("#0.00%");
                return mFormat.format(value);
            }
        });

        axisRightLine.setDrawGridLines(false);
        axisRightLine.setDrawAxisLine(false);
        axisRightLine.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);

        //背景线
        xAxisLine.setGridColor(ChartThemeUtil.instance().color_line);
        xAxisLine.setAxisLineColor(ChartThemeUtil.instance().color_line);
        xAxisLine.setTextColor(ChartThemeUtil.instance().color_text);
        axisLeftLine.setGridColor(ChartThemeUtil.instance().color_line);
        axisLeftLine.setTextColor(ChartThemeUtil.instance().color_text);
        axisRightLine.setAxisLineColor(ChartThemeUtil.instance().color_line);
        axisRightLine.setTextColor(ChartThemeUtil.instance().color_text);
        axisRightLine.setSideNeedPathEffect(false);
        axisRightLine.setNeedOffset(false);




        lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {

//                lineChart.setHighlightValue(new Highlight(h.getXIndex(), 0));
                lineChart.highlightValues(new Highlight[]{h});

                // lineChart.setHighlightValue(h);
            }

            @Override
            public void onNothingSelected() {
                lineChart.highlightValue(null);
            }
        });

    }



    public void setData(DataParse mData) {
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",mData="+mData);
        this.mData=mData;
        refreshProductDecimalNum(mData.getProductCode());//设置小数位
        setMarkerView(mData);
        stringSparseArray=setXLabels();
        setShowLabels(stringSparseArray);
        Log.e("###", mData.getDatas().size() + "ee");
        if (mData.getDatas().size() == 0) {
            lineChart.setNoDataText("暂无数据");
            return;
        }

        //设置y左右两轴最大最小值
        if(mData.getMinValue()==mData.getMaxValue()){
            axisLeftLine.setAxisMinValue((float)mData.getMinValue());
            axisRightLine.setAxisMaxValue(mData.getPercentMax()+0.000001f);
            axisRightLine.setAxisMinValue(0);
        }else {
            axisLeftLine.setAxisMinValue((float)mData.getMinValue());
            axisLeftLine.setAxisMaxValue((float)mData.getMaxValue());
            axisRightLine.setAxisMinValue(mData.getPercentMin());
            axisRightLine.setAxisMaxValue(mData.getPercentMax());

        }

        //左Y的保留数位
        axisLeftLine.setValueFormatter(new YAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, YAxis yAxis) {
                return mDecimalFormat.format(value);
            }
        });


        /** 取消多余的基准线 **/
        if(axisRightLine.getLimitLines().size()<1)
        {
            //基准线
            LimitLine ll = new LimitLine(0);
            ll.setLineWidth(0.3f);
            int limitLineColor = axisRightLine.getLimitLineColor();
            ll.setLineColor(limitLineColor == 0 ? ChartThemeUtil.instance().color_line : limitLineColor);
            //ll.enableDashedLine(10f, 10f, 0f);
            axisRightLine.addLimitLine(ll);
            //axisRightLine.setBaseValue(0);
        }

        ArrayList<Entry> lineCJEntries = new ArrayList<>();
        ArrayList<Entry> lineJJEntries = new ArrayList<>();
        ArrayList<String> dateList = new ArrayList<>();
        ArrayList<String> xVals = new ArrayList<>();
        Log.e("##", Integer.toString(xVals.size()));
        for (int i = 0, j = 0; i < mData.getDatas().size(); i++, j++) {
           /* //避免数据重复，skip也能正常显示
            if (mData.getDatas().get(i).time.equals("13:30")) {
                continue;
            }*/
            MinutesBean t = mData.getDatas().get(j);

            if (t == null) {
                lineCJEntries.add(new Entry(Float.NaN, i));
                lineJJEntries.add(new Entry(Float.NaN, i));
                continue;
            }
            if (!TextUtils.isEmpty(stringSparseArray.get(i)) &&
                    stringSparseArray.get(i).contains("/")) {
                i++;
            }
            lineCJEntries.add(new Entry(mData.getDatas().get(i).cjprice, i));
            lineJJEntries.add(new Entry(mData.getDatas().get(i).avprice, i));
            // dateList.add(mData.getDatas().get(i).time);
        }
        d1 = new LineDataSet(lineCJEntries, "成交价");
        d2 = new LineDataSet(lineJJEntries, "均价");
        d1.setDrawValues(false);
        d2.setDrawValues(false);


        d1.setCircleRadius(0);
        d2.setCircleRadius(0);
        d1.setColor(ChartThemeUtil.instance().color_time_line);
        d2.setColor(ChartThemeUtil.instance().color_avg_line);
        d1.setHighLightColor(ChartThemeUtil.instance().color_time_line);
        d2.setHighlightEnabled(false);
        d1.setDrawFilled(true);
        d1.setFillColor(ChartThemeUtil.instance().color_time_shadow);
        d1.setFillAlpha(60);//default: 85

        //谁为基准
        d1.setAxisDependency(YAxis.AxisDependency.LEFT);
        // d2.setAxisDependency(YAxis.AxisDependency.RIGHT);
        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);
        sets.add(d2);
        /*注老版本LineData参数可以为空，最新版本会报错，修改进入ChartData加入if判断*/
        LineData cd = new LineData(getMinutesCount(), sets);
        lineChart.setData(cd);

        lineChart.invalidate();//刷新图



    }


    private SparseArray<String> setXLabels() {
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
        SparseArray<String> xLabels = new SparseArray<>();
        for(int i=0;i<5;i++){
            xLabels.put(i*360, StringFormatter.instance().secToTimeSimple(mStartTime+i*3600*6));
        }
        return xLabels;
    }


    public void setShowLabels(SparseArray<String> labels) {
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",labels="+labels);
        xAxisLine.setXLabels(labels);

    }

    public String[] getMinutesCount() {
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
        return new String[1441];
    }

    private void setMarkerView(DataParse mData) {
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",mData="+mData);
        lineChart.setMarker(leftMarkerView, rightMarkerView,bottomMarkerView, mData);
    }

    private void DecimalFormat(int num){
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",num="+num);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < num; i++) {
            sb.append(String.valueOf("0"));
        }
        if(num==0){
            mDecimalFormat = new DecimalFormat("#0");
        }else {
            mDecimalFormat = new DecimalFormat("#0"+"."+sb.toString());
        }
    }

    @Override public void setProductDecimalNum(int num) {

    }

    @Override public void refreshData(GTTIndicatorsModel indicatorsModel, boolean main) {

    }

    @Override public void refreshCandleData() {

    }

    @Override public void setStartTime(int startTime) {
        mStartTime=startTime;
    }

    @Override public void refreshProductDecimalNum(int num) {
        Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",num="+num);
        DecimalFormat(num);
        axisLeftLine.setValueFormatter(new YAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, YAxis yAxis) {
                return mDecimalFormat.format(value);
            }
        });
        lineChart.refreshProductDecimalNum(mDecimalFormat);
    }

}
